package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.lang.hash.Hash;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.text.Format;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.USER_SIGN_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1校验手机号格式
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        //2失败，直接返回格式不对
        if (phoneInvalid){
            return Result.fail("手机格式不对");
        }
        //3成功，基于utils生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4保存验证码，使用redis
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5发送验证码
        log.debug("已向手机号："+phone+"的用户发送验证码："+code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1校验手机号——获取验证码只证明当时手机号是对的，后面可能又修改了
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(loginForm.getPhone());
        if (phoneInvalid){
            return Result.fail("手机格式不对");
        }
        //2校验验证码
        //从redis中获取验证码
//        String cacheCode = (String) session.getAttribute("code");

        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + loginForm.getPhone());
        if (cacheCode == null || !cacheCode.equals(loginForm.getCode())){
            //3不一致
            return Result.fail("验证码错误");
        }
        //4一致，查询用户是否存在
        //基于mybatis-plus
        User user = query().eq("phone", loginForm.getPhone()).one();
        //5不存在,创建用户
        if (user == null){
            user = createUserWithPhone(loginForm.getPhone());
        }
        //6结果保存到redis中
        //将user转成hashmap
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //stringRedisTemplate默认key和value都是string，而userDTO中id是long，因此要转换
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //生成token
        String token = UUID.randomUUID().toString(true);
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,userMap);
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //获取用户
        UserDTO user = UserHolder.getUser();
        //获取今天的本月的第几天
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        //签到
        stringRedisTemplate.opsForValue().setBit(USER_SIGN_KEY+user.getId().toString()+":"+keySuffix,dayOfMonth-1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取本月签到情况
        UserDTO user = UserHolder.getUser();
        //获取今天的本月的第几天
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        List<Long> list = stringRedisTemplate.opsForValue()
                .bitField(USER_SIGN_KEY + user.getId().toString() + ":" + keySuffix,
                        BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (list==null||list.isEmpty()){
            return Result.ok(0);
        }
        //只用了一个get
        Long num = list.get(0);
        if (num==null){
            return Result.ok(0);
        }
        //遍历
        int count = 0;
        while (true){
            if ((num&1)==0){
                break;
            }else {
                count++;
            }
            //右移一位
            num>>>=1;
        }
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        User user = User.builder()
                .nickName(SystemConstants.USER_NICK_NAME_PREFIX+RandomUtil.randomString(5))
                .phone(phone)
                .build();
        save(user);
        return user;
    }
}
